package com.tanovo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tanovo.bo.Token;
import com.tanovo.bo.UserCore;
import com.tanovo.domain.*;
import com.tanovo.mapper.OauthClientTokenMapper;
import com.tanovo.mapper.ResourcesMapper;
import com.tanovo.service.IAuthTokenService;
import com.tanovo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AuthTokenServiceImpl implements IAuthTokenService {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private OauthClientTokenMapper oauthClientTokenMapper;


    @Override
    public UserCore checkToken(String token) {
        //todo 这里要加redis 缓存
        OauthClientToken oauthClientToken = this.getByToken(token);
        if (oauthClientToken == null) {
            log.info("获取不到对应的token:" + token);
            return null;
        }
        User user = iUserService.getUserById(oauthClientToken.getUserId());
        if (user == null) {
            log.info("Token对应的用户不存在:" + token);
            return null;
        }
        Date date = new Date();
        if (date.compareTo(oauthClientToken.getExpiredTime()) > 0) {
            log.info("Token超时，用户:{}", JSONObject.toJSONString(user));
            return null;
        }
        UserCore userCore = new UserCore();
        BeanUtils.copyProperties(user, userCore);
        userCore.setClientId(oauthClientToken.getClientId());
        userCore.setCompanyId(oauthClientToken.getCompanyId());
        return userCore;
    }

    @Override
    public OauthClientToken getByToken(String token) {
        OauthClientTokenExample example = new OauthClientTokenExample();
        example.createCriteria().andTokenEqualTo(token);
        List<OauthClientToken> tokenList = oauthClientTokenMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(tokenList)) {
            return null;
        }
        return tokenList.get(0);
    }

}
